package com.lq.util;

import javax.servlet.http.Part;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 传入一个输入流和一个目标路径，就可以将文件输入到那里去
 */
public class IOUtil {
    public static void copy(InputStream inputStream, String path){

        //经典操作，将变量定义在try外面
        FileOutputStream fileOutputStream = null;
        try{
            //经典操作将读取文件，并写入到指定路径
            fileOutputStream = new FileOutputStream(path);
            byte[] bytes = new byte[1024 * 1024];
            int len;
            while ((len = inputStream.read(bytes)) != -1) {
                fileOutputStream.write(bytes, 0, len);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally{
            //最后通过判断输入输出流是否为空进行关闭
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if(fileOutputStream != null){
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
